/* 用户路由器文件 */

//引入express模块
const express = require("express");
//引入fs模块
const fs = require("fs");
//引入连接池pool.js
const pool = require("../pool.js");
//引入邮箱发送文件email.js
const sendEmail = require("../email/email.js");
//引入上传头像文件uploadImg.js
const { upload } = require("../uploadImg/uploadImg.js");
//创建路由器对象
const router = express.Router();

//登录接口 post(/user/login)
router.post("/login", function (req, res) {
  let $loginName = req.body.loginName; //登录账号
  let $loginPassword = req.body.loginPassword; //登录密码
  //非空验证
  if (!$loginName) {
    res.send({
      data: {
        status: 0,
        message: "登录账号不能为空",
      },
    });
    return;
  }
  if (!$loginPassword) {
    res.send({
      data: {
        status: 0,
        message: "登录密码不能为空",
      },
    });
    return;
  }
  let sql = "SELECT * FROM user WHERE loginName= ? AND loginPassword = ?"; //以登录账号与密码查询
  pool.query(sql, [$loginName, $loginPassword], function (err, result) {
    if (err) throw err; //抛出异常
    // 若查询无此账号，则返回登录失败
    if (result.length == 0) {
      res.send({
        data: {
          status: 0,
          message: "登录账号或密码错误",
        },
      });
    } else {
      //若有此账号,则返回登录成功
      // 查询结果
      let searchResult = result[0];
      let $id = searchResult.id;
      let $headImg = searchResult.headImg;
      let $userName = searchResult.userName;
      res.send({
        data: {
          status: 1,
          message: "登录成功",
          userinfo: {
            id: $id,
            userName: $userName,
            headImg: $headImg,
          },
        },
      });
    }
  });
});

//保存邮箱、验证码信息
let codeNews = {
  email: "", //邮箱
  code: "", //验证码
  time: "", //时间
};
//邮箱验证码 get(/user/getCode)
router.get("/getCode", function (req, res) {
  let $email = req.query.email; //注册邮箱
  //非空验证
  if (!$email) {
    res.send({
      data: {
        status: 0,
        message: "邮箱不能为空",
      },
    });
    return;
  }
  //查询邮箱是否已注册
  let sql = "SELECT * FROM user WHERE email = ?"; //以邮箱去查询
  pool.query(sql, [$email], function (err, result) {
    if (err) throw err; //抛出异常
    // 若查询无此邮箱账号，则返回获取成功并发送验证码
    if (result.length == 0) {
      codeNews.email = $email; //注册邮箱
      codeNews.code = sendEmail.send($email); //发送的验证码
      codeNews.time = new Date().getTime(); //生成验证码的时间戳
      res.send({
        data: {
          status: 1,
          message: "获取成功并发送验证码完成",
        },
      });
    } else {
      //若有此账号,则返回邮箱已注册
      res.send({
        data: {
          status: 0,
          message: "此邮箱已注册",
        },
      });
    }
  });
});

//注册接口 post(/user/register)
router.post("/register", function (req, res) {
  let $registerName = req.body.registerName;
  let $registerPassword = req.body.registerPassword;
  let $email = req.body.email;
  let $verCode = req.body.verCode;
  //非空验证
  if (!$registerName) {
    res.send({
      data: {
        status: 0,
        message: "注册账号不能为空",
      },
    });
    return;
  }
  if (!$registerPassword) {
    res.send({
      data: {
        status: 0,
        message: "注册密码不能为空",
      },
    });
    return;
  }
  if (!$email) {
    res.send({
      data: {
        status: 0,
        message: "注册邮箱不能为空",
      },
    });
    return;
  }
  if (!$verCode) {
    res.send({
      data: {
        status: 0,
        message: "验证码不能为空",
      },
    });
    return;
  }
  let nowTime = new Date().getTime(); //注册时的时间戳
  //判断邮箱是否为获取验证码邮箱 不区分大小写
  if ($email.toUpperCase() !== codeNews.email.toUpperCase()) {
    res.send({
      data: {
        status: 0,
        message: "注册邮箱错误",
      },
    });
    return;
  }
  //判断验证码是否正确  不区分大小写
  if ($verCode.toUpperCase() !== codeNews.code.toUpperCase()) {
    res.send({
      data: {
        status: 0,
        message: "验证码错误",
      },
    });
    return;
  }
  //判断验证码时效性
  let Timeliness = 24 * 60 * 60 * 1000; //24小时转成毫秒
  let timeDiff = Number(nowTime) - Number(codeNews.time); //时间戳比
  if (timeDiff > Timeliness) {
    res.send({
      data: {
        status: 0,
        message: "验证码已过期，请重新获取",
      },
    });
    return;
  }
  // 查询用户账号是否已注册
  let sql = "SELECT * FROM user WHERE loginName = ?"; //以登录账号去查询
  pool.query(sql, [$registerName], function (err, result) {
    if (err) throw err; //抛出异常
    // 若查询无此账号用户，则写入数据库并返回注册成功
    if (result.length == 0) {
      // 生成用户昵称
      let $userName = $registerName + "_" + new Date().getTime();
      // 长度为6位
      $userName = $userName.substr(0,6);
      let sql =
        "INSERT INTO user(loginName,loginPassword,userName,email) VALUES(?,?,?,?);"; //将注册信息写入数据库
      pool.query(
        sql,
        [$registerName, $registerPassword, $userName, $email],
        function (err, results) {
          if (err) throw err; //抛出异常
          res.send({
            data: {
              status: 1,
              message: "注册成功",
            },
          });
        }
      );
    } else {
      //若有此账号,则返回用户已存在
      res.send({
        data: {
          status: 0,
          message: "该用户已存在",
        },
      });
    }
  });
});

// 上传头像接口 post(/user/uploadImg)
router.put("/uploadImg", upload.single("headImg"), function (req, res) {
  // 用户id
  let $id = req.body.id;
  //非空验证
  if (!$id) {
    res.send({
      data: {
        status: 0,
        message: "用户id不能为空",
      },
    });
    return;
  }
  // 判断文件类型与大小, 格式：["jpg", "jpeg", "png", "gif"]   大小：小于200kb
  let types = ["jpg", "jpeg", "png", "gif"];
  let MaxSize = 1024 * 200;
  // 获取上传后的文件路径
  let $path = req.file.path;
  // 获取图片类型
  let $type = req.file.mimetype.split("/")[1];
  // 获取图片大小
  let $size = req.file.size;
  // 如果格式错误
  if (!types.includes($type)) {
    // 删除文件
    fs.unlink($path, function (err) {
      if (err) throw err;
    });
    res.send({
      data: {
        status: 0,
        message: "类型错误",
      },
    });
    return;
  }
  // 如果文件过大
  if ($size > MaxSize) {
    // 删除文件
    fs.unlink($path, function (err) {
      if (err) throw err;
    });
    res.send({
      data: {
        status: 0,
        message: "尺寸过大",
      },
    });
    return;
  }
  // 保存后的文件名
  let name = req.file.filename;
  // 网络路径
  let imgUrl = "http://bigtree.host/public/img/" + name;
  // sql语句
  let sql = "UPDATE user SET headImg=? WHERE id=? ;"; //以id修改
  pool.query(sql, [imgUrl, $id], function (err, result) {
    if (err) throw err; //抛出异常
    // 若修改成功
    if (result.affectedRows > 0) {
      res.send({
        data: {
          status: 1,
          message: "上传成功",
          headImgUrl: imgUrl,
        },
      });
    } else {
      //修改失败
      res.send({
        data: {
          status: 0,
          message: "上传失败",
        },
      });
    }
  });
});

//导出路由器对象，供web服务器使用
module.exports = router;
